<?php

namespace App\Admin\Controllers\Admin;

use App\Models\FlowChannel;
use App\Models\Setting as SettingModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Database\Eloquent\Collection;

class FlowChannelController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '流量渠道';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new FlowChannel());
        $api_url = json_decode(SettingModel::query()->firstOrCreate(['key' => 'api_url'], ['value' => null])->value);

        $grid->column('id', __('Id'));
        $grid->column('name', __('渠道名称'));
        $grid->column('rate', __('结算比例'))->editable();
        $grid->column('param', __('渠道参数'));
        $grid->model()->collection(function (Collection $collection) use($api_url){


            foreach($collection as $item) {
                $item->visit_url = env('APP_URL').'/flow_channel/detail?param=' . $item->param;  //给集合增加渠道地址字段
                $item->api =  $api_url.'?param=' . $item->param;//增加接口获取字段
            }


            return $collection;
        });
        $grid->column('visit_url', __('访问地址'))->link();
        $grid->column('api', __('接口地址'))->link();
        $grid->column('created_at', __('创建时间'));

        $grid->actions(function($action){
           $action->disableDelete();
            $action->disableView();
        });
        return $grid;
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new FlowChannel());

        $form->text('name', __('渠道名称'))->required();
        $form->rate('rate', __('结算比例'))->required();
        $form->saving(function (Form $form){
            $form->model()->param = md5(uniqid());//生成唯一渠道参数
        });
        return $form;
    }
}
